#include <iostream>
#include <jsoncpp/json/json.h>
//#include "cJSON.h"
#include <string.h>
#include <curl/curl.h>
#include <stdlib.h>
using namespace std;
using namespace Json;



#define N 128

//构造json请求报文
string robot_make_request( char * apikey,char * text);
string robot_make_request( char * apikey, char * text)
{
	//判断输入的字符串长度不为0
	if(strlen(text)==0)
	{
		return NULL;
	}

	Value json;

	json["perception"]["inputText"]["text"]=text;
	json["userInfo"]["apiKey"]=apikey;
	json["userInfo"]["userId"]="gaomin";

	StyledWriter my_write;
	string request=my_write.write(json);
	return request;


	//将JSON数据结构转为字符串
//	return cJSON_Print(request);
}

//作业:发送请求报文给图灵机器人服务器,等待服务器的响应报文
char * robot_send_request(string request);
char * robot_send_request(string request)
{

	FILE * fp=NULL;
	char* response;
//	string * response;
	size_t resplen;
	fp=open_memstream(&response,&resplen);	
	//fp=fopen("1.txt","w");

	if(NULL==fp)
	{
		perror("open file");
		return NULL;
	}

	//1.初始化curl
	CURL * curl=curl_easy_init();
	if(NULL==curl)
	{
		perror("inint error");
		return NULL;
	}
	//2.发送到百度云的字符串需要两次URL编码
	//3.
	//char * temp=curl_easy_escape(curl,requ);

	curl_easy_setopt(curl,CURLOPT_URL,"http://openapi.tuling123.com/openapi/api/v2");
	curl_easy_setopt(curl,CURLOPT_POST,1);
	curl_easy_setopt(curl,CURLOPT_POSTFIELDS,request.c_str());
	curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
	CURLcode error=curl_easy_perform(curl);

	if(error!=CURLE_OK)
	{
		perror("perform error\n");
		curl_easy_cleanup(curl);
		free(response);
		fclose(fp);
	}



	fflush(fp);

	curl_easy_cleanup(curl);
	fclose(fp);
//	free(response);

	return response;
	
}

//解析response

void robot_process_response(const char * response);
void robot_process_response(const char * response)
{


	string result;
	result.append(response);
	Value json;
	Reader myRead;
	myRead.parse(result,json);

	//cout<<"json"<<json<<endl;

	int i=0;
	int code=json["intent"]["code"].asInt();
//	cout<<"code"<<code<<endl;
	if(code>10000){
	for(i=0;i<json["results"].size();i++)
	{

		cout<<json["results"][i]["values"]["text"]<<endl;
	}
	}
}

int main(void)
{

	char line[N]={'\0'};
	
	 char * apikey="dee1af6fff0d4c94a389ecc8574972c3";
	while(fgets(line,sizeof(line),stdin)!=NULL)
	{
		//构造请求报文
		string request=robot_make_request(apikey,line);
	/*	if(NULL==request)
		{
			continue;
		}*/
		
		//将请求报文发送给图灵机器人
	//	cout<<"request:"<<request;
		char * response=robot_send_request(request);
	//	printf("response2=%s\n",response);
		robot_process_response(response);
		//free(response);
	}

	return 0;
}











